#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
数据库模型定义
"""

from flask_sqlalchemy import SQLAlchemy
from flask_login import UserMixin
from werkzeug.security import generate_password_hash, check_password_hash
from datetime import datetime

db = SQLAlchemy()

class AdminUser(UserMixin, db.Model):
    """
    管理员用户模型
    """
    __tablename__ = 'admin_users'
    
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)
    password_hash = db.Column(db.String(255), nullable=False)
    is_active = db.Column(db.Boolean, default=True)
    is_superuser = db.Column(db.Boolean, default=False)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    last_login = db.Column(db.DateTime)
    
    def set_password(self, password):
        """设置密码"""
        self.password_hash = generate_password_hash(password)
    
    def check_password(self, password):
        """验证密码"""
        return check_password_hash(self.password_hash, password)
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'username': self.username,
            'email': self.email,
            'is_active': self.is_active,
            'is_superuser': self.is_superuser,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None,
            'last_login': self.last_login.isoformat() if self.last_login else None
        }
    
    def __repr__(self):
        return f'<AdminUser {self.username}>'

class BackgroundConfig(db.Model):
    """
    客户端背景图片配置模型
    """
    __tablename__ = 'background_configs'
    
    id = db.Column(db.Integer, primary_key=True)
    config_type = db.Column(db.String(50), nullable=False)  # 'header' 或 'background'
    image_url = db.Column(db.String(500), nullable=True)  # 图片URL
    image_filename = db.Column(db.String(255), nullable=True)  # 原始文件名
    is_active = db.Column(db.Boolean, default=True)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'config_type': self.config_type,
            'image_url': self.image_url,
            'image_filename': self.image_filename,
            'is_active': self.is_active,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None
        }
    
    def __repr__(self):
        return f'<BackgroundConfig {self.config_type}: {self.image_filename}>'

def init_db(app):
    """
    初始化数据库
    """
    db.init_app(app)
    
    with app.app_context():
        # 创建所有表
        db.create_all()
        
        # 检查是否存在超级管理员，如果不存在则创建默认的
        if not AdminUser.query.filter_by(is_superuser=True).first():
            admin = AdminUser(
                username='admin',
                email='admin@example.com',
                is_superuser=True
            )
            admin.set_password('admin123')  # 默认密码，建议首次登录后修改
            db.session.add(admin)
            db.session.commit()
            print("✅ 已创建默认超级管理员账户: admin / admin123")
        
        print("✅ 数据库初始化完成")